package com.ruoyi.common.utils;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Dict;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 对Jackson中的方法进行了简单封装
 *
 * @author CaoChenLei
 */
@Slf4j
public final class JsonUtils {
    private JsonUtils() {
    }

    private static final ObjectMapper OBJECT_MAPPER = SpringUtils.getBean(ObjectMapper.class);

    public static ObjectMapper getObjectMapper() {
        return OBJECT_MAPPER;
    }

    public static void writeJsonToFile(File file, Object object) {
        ObjectMapper objectMapper = new ObjectMapper();

        try {
            objectMapper.writeValue(file, object);
            System.out.println("JSON文件写入成功！");
        } catch (IOException e) {
            System.out.println("JSON文件写入失败：" + e.getMessage());
        }
    }

    public static String toJsonString(Object object) {
        try {
            return OBJECT_MAPPER.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    public static JsonNode toJsonNode(Object object) {
        return OBJECT_MAPPER.valueToTree(object);
    }

    public static <T> T parseJsonNodeToObject(JsonNode jsonNode, Class<T> beanType) {
        try {
            return OBJECT_MAPPER.treeToValue(jsonNode, beanType);
        } catch (JsonProcessingException e) {
            return null;
        }

    }

    /**
     * 将指定对象序列化为一个json字符串
     *
     * @param obj 指定对象
     * @return 返回一个json字符串
     */
    public static String toString(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj instanceof String) {
            return Convert.toStr(obj);
        }
        try {
            return OBJECT_MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("json序列化出错：" + obj, e);
            return null;
        }
    }

    public static <T> T parseJsonString(String jsonStr, Class<T> beanType) {
        try {
            return OBJECT_MAPPER.readValue(jsonStr, beanType);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    /**
     * 将指定json字符串解析为指定类型对象
     *
     * @param json   json字符串
     * @param tClass 指定类型
     * @return 返回一个指定类型对象
     */
    public static <T> T toBean(String json, Class<T> tClass) {
        try {
            return OBJECT_MAPPER.readValue(json, tClass);
        } catch (IOException e) {
            log.error("json解析出错：" + json, e);
            return null;
        }
    }

    /**
     * 将指定输入流解析为指定类型对象
     *
     * @param inputStream 输入流对象
     * @param tClass      指定类型
     * @return 返回一个指定类型对象
     */
    public static <T> T toBean(InputStream inputStream, Class<T> tClass) {
        try {
            return OBJECT_MAPPER.readValue(inputStream, tClass);
        } catch (IOException e) {
            log.error("json解析出错：" + inputStream, e);
            return null;
        }
    }

    /**
     * 将指定json字符串解析为指定类型集合
     *
     * @param json   json字符串
     * @param eClass 指定元素类型
     * @return 返回一个指定类型集合
     */
    public static <E> List<E> toList(String json, Class<E> eClass) {
        try {
            return OBJECT_MAPPER.readValue(json, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, eClass));
        } catch (IOException e) {
            log.error("json解析出错：" + json, e);
            return null;
        }
    }

    public static <T> List<T> parseJsonToList(String jsonArrayStr, Class<T> beanType) {
        try {
            return OBJECT_MAPPER.readValue(jsonArrayStr, new TypeReference<List<T>>() {
            });
        } catch (JsonProcessingException e) {
            log.error("json解析出错：" + jsonArrayStr, e);
            return null;
        }
    }

    /**
     * 将指定json字符串解析为指定键值对类型集合
     *
     * @param json   json字符串
     * @param kClass 指定键类型
     * @param vClass 指定值类型
     * @return 返回一个指定键值对类型集合
     */
    public static <K, V> Map<K, V> toMap(String json, Class<K> kClass, Class<V> vClass) {
        try {
            return OBJECT_MAPPER.readValue(json, OBJECT_MAPPER.getTypeFactory().constructMapType(Map.class, kClass, vClass));
        } catch (IOException e) {
            log.error("json解析出错：" + json, e);
            return null;
        }
    }

    public static Map<String, Object> parseJsonToMap(String jsonStr) {
        try {
            return OBJECT_MAPPER.readValue(jsonStr, new TypeReference<Map<String, Object>>() {
            });
        } catch (JsonProcessingException e) {
            return null;
        }

    }

    public JsonNode parseJsonToJsonNode(String jsonStr) {
        try {
            return OBJECT_MAPPER.readTree(jsonStr);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 将指定json字符串解析为一个复杂类型对象
     *
     * @param json json字符串
     * @param type 复杂类型
     * @return 返回一个复杂类型对象
     */
    public static <T> T nativeRead(String json, TypeReference<T> type) {
        try {
            return OBJECT_MAPPER.readValue(json, type);
        } catch (IOException e) {
            log.error("json解析出错：" + json, e);
            return null;
        }
    }


    public static Dict parseMap(String text) {
        if (StringUtils.isBlank(text)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructType(Dict.class));
        } catch (MismatchedInputException e) {
            // 类型不匹配说明不是json
            return null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static List<Dict> parseArrayMap(String text) {
        if (StringUtils.isBlank(text)) {
            return null;
        }
        try {
            return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, Dict.class));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> List<T> parseArray(String text, Class<T> clazz) {
        if (StringUtils.isEmpty(text)) {
            return new ArrayList<>();
        }
        try {
            return OBJECT_MAPPER.readValue(text, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}